package com.dsr.interceptor;

import com.dsr.exception.FlowerException;
import com.dsr.util.JwtUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

public class MyInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            Map<String, String> collect = Arrays.stream(cookies).
                    collect(Collectors.toMap(Cookie::getName, Cookie::getValue));
            if(collect.containsKey("token")){
                String token = collect.get("token");
                try {
                    JwtUtil.verify(token);
                    request.setAttribute("token",token);
                }catch (Exception e){
                    throw new FlowerException(HttpStatus.UNAUTHORIZED,"登录失效");
                }
            }
            return true;
        }else {
            throw new FlowerException(HttpStatus.UNAUTHORIZED,"登录失效");
        }

    }

}
